// @ts-nocheck
// src/pages/hospital/hospitalSet/index.tsx
import React, { useState, useEffect, Key,useRef } from "react";
import { Card, Form, Input, Button, Table, Tooltip, message, Modal,Checkbox, Divider } from "antd";
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import { SearchOutlined, EditOutlined, DeleteOutlined ,UserOutlined,GithubOutlined} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

import { useTranslation } from "react-i18next";

import { reqGetHospitalList, reqRemoveHospital, reqBatchRemoveHospitalList,reqAddHospital,reqUpdateHospital,reqGetRoles,reqToRoles} from "@api/hospital/hospitalSet";
import type { HospitalList, HospitalItem } from "@api/hospital/model/hospitalSetTypes";

import "./index.less";
import Password from "antd/lib/input/Password";
import { arrayBuffer } from "stream/consumers";

function HospitalSet() {
 
  // 
  // const value1 = useRef(null)
  // const value2 = useRef(null)
  // const value3 = useRef(null)
  const [username, setusername] = useState('累死我了')
  const [nickName, setnickName] = useState('小王子')
  const [password, setpassword] = useState('123')
  const [userid,setuserid]=useState(null)
  const [isModalOpenAgain, setIsModalOpenAgain] = useState(false);
  //搜索框
  const { Search } = Input;
  const { t } = useTranslation(["hospitalSet"]);
  // loading
  const [loading, setLoading] = useState(false);
  // 定义医院列表数据和类型
  const [hospitalList, setHospitalList] = useState<HospitalList>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [reslist,setReslist] = useState([])
  //dialog框
  const [isModalOpen, setIsModalOpen] = useState(false);
  //改变用户的title
  const [title,settitle]=useState("添加用户")
  //角色ID
  const [roleId,setRoleId]=useState("")
  
  // const [list] = useState(res.items)
  // 封装公共请求函数
  const getHospitalList = async (page: number, limit: number) => {
    // 发送请求开启loading
    // setLoading(true);
    // 读取表单数据
    const { hosname, hoscode } = form.getFieldsValue();
    // 发送请求携带上另外的参数
    const res = await reqGetHospitalList({ page, limit, hosname, hoscode }); 
    setReslist(res.items);
    // 更新页码
    setCurrent(page);
    setPageSize(limit);
    // 更新总数
    // setTotal(res.total);
    // // 更新数据
    // setHospitalList(res.records);
    // 请求完成结束loading
    // setLoading(false);
  };
    //dialog组件
      const showModal = () => {
        setIsModalOpen(true);
        settitle('添加用户')
      };
      //username回调
      const handleUsernameChange = (e) => {

        // 将最新输入的值更新到name状态
        const username = e.target.value
        setusername(e.target.value)
    
        // 对name进行实时检验: 不能超过6位
        // if (username.length>6) {
        //   alert('用户名不能超过6位')
        // }
      }
      //nickName回调
      const handleNicknameChange = (e) => {

        // 将最新输入的值更新到name状态
        const nickName = e.target.value
        setnickName(e.target.value)
    
      }
      //password回调
      const handlePasswordChange = (e) => {

        // 将最新输入的值更新到name状态
        const password = e.target.value
        setpassword(e.target.value)
    
        // 对name进行实时检验: 不能超过6位
        // if (username.length>6) {
        //   alert('用户名不能超过6位')
        // }
      }
      //点击确定按钮
      const handleOk = async() => {
        setIsModalOpen(false);
         // 点击确定将对话框的数据传过去

        //  console.log(value1.current.input.value,value2.current.input.value,value3.current.input.value)
         //{username: "11111111111111111", nickName: "1233333333333", password: 3332111111111}
        
        //  const username=value1.current.input.value
        //  const nickName=value2.current.input.value
        //  const password=value3.current.input.value
        if(userid){
          const id = userid
          // const username=username
          // const nickName = nickName
          await reqUpdateHospital({username,nickName,id}) 
          setuserid("")
          settitle("添加用户")
        }else{
          // console(1)
          // const wocao={username,nickName,password}
          // console.log(wocao)
         await reqAddHospital({username,nickName,password})
         settitle("修改用户")  
        }
        
        await getHospitalList(current, pageSize);
      };
      //点击确定按钮
      // const handleOk =async (value1,value2,value3) => {
      //   setIsModalOpen(false);
         // 点击确定将对话框的数据传过去

        //  console.log(value1.current.input.value,value2.current.input.value,value3.current.input.value)
         //{username: "11111111111111111", nickName: "1233333333333", password: 3332111111111}
        
        //  const username=value1.current.input.value
        //  const nickName=value2.current.input.value
        //  const password=value3.current.input.value
        //  const wocao={username,nickName,password}
        //  console.log(wocao)
        // const res= await reqAddHospital(wocao)
        // getHospitalList(current, pageSize);
      // };

      const handleCancel = () => {
        setIsModalOpen(false);
      };
    //点击修改按钮

  // 一上来发送请求
  useEffect(() => {
    getHospitalList(current, pageSize);
    // 注意：依赖数组中不能有current, pageSize
    // 因为会导致请求发送两次
    // console.log(value1.current)
  }, []);

  // 点击查询按钮，触发的回调函数
  // values就是收集到的表单数据
  const onFinish = () => {
    // 发送请求，获取最新数据展示
    getHospitalList(current, pageSize);
  };
  //点击展示全部角色模态框


  // 清空表单
  const reset = () => {
    // 清空表单内容
    form.resetFields();
    // 重新获取数据展示
    getHospitalList(1, 5);
  };

  // 列
  const columns = [
    {
      // 标题
      title: t("index"),
      width: 70,
      align: "center" as "center",
      // 渲染什么数据
      // dataIndex写啥？看接口文档返回数据的格式，数据返回叫啥就写啥
      // 接口文档没有的就自己定义，保证唯一即可
      // dataIndex: "index",
      render: (_x: any, _y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: t("用户名"),
      dataIndex: "username",
    },
    {
      title: t("用户昵称"),
      dataIndex: "nickName",
    },
    {
      title: t("用户列表"),
      dataIndex: "roleName",
    },
    {
      title: t("创建时间"),
      dataIndex: "gmtCreate",
    },
    {
      title: t("更新时间"),
      dataIndex: "gmtModified",
    },

    {
      title: t("操作"),
      // 固定在右侧
      // fixed: 'right', // 报错，会自动将类型推论为string
      fixed: "right" as "right", // 将类型断言为 'right' 字符串字面量类型就好
      width: 220,
      // 写了dataIndex就只能得到某个数据
      // 不写dataIndex，render方法就能接收到整行数据
      // 类型为单个医院数据
      render: (row: HospitalItem) => {
        return (
          <>
              <Tooltip placement="top" title="分配角色" >
              <Button type="primary" onClick={()=>showModalAgain(row)} icon={<GithubOutlined />} style={{marginRight:'10px'}}>
                  
              </Button>
              <Modal title="分配角色" visible={isModalOpenAgain} onOk={handleOkAgain} onCancel={handleCancelAgain}>
              用户名<input  value={username} onChange={handleUsernameChange} disabled/>
              <div></div>
              <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
                  全选
              </Checkbox>
                <Divider />
              
              <CheckboxGroup options={options}  value={checkedList} onChange={onChange}></CheckboxGroup>
              </Modal>
              {/* <Button className="hospital-btn" type="primary" icon={<UserOutlined />} onClick={goAssignHospital(row.id)} /> */}
            </Tooltip>
            <Tooltip placement="top" title={t("修改角色")}>
              <Button className="hospital-btn" type="primary" icon={<EditOutlined />} onClick={()=>goUpdateHospital(row)} />
            </Tooltip>
            <Tooltip placement="top" title={t("删除用户")}>
              <Button className="hospital-btn" type="primary" danger icon={<DeleteOutlined />} onClick={removeHospital(row.id)} />
            </Tooltip>
          </>
        );
      },
    },
  ];

  // 删除医院
  const removeHospital = (id: number) => {
    return async () => {
      // 发送请求，只会删除服务器数据，客户端数据没变
      await reqRemoveHospital(id);
      message.success("删除医院成功");
      // 重新获取最新医院列表即可
      getHospitalList(current, pageSize);
    };
  };

  // 功能代码尽量放一起
  const navigate = useNavigate();

  // 跳转到添加医院组件
  const goAddHospital = () => {
    // navigate('/syt/hospital/hospitalSet/add', { replace: true }) // replace
    navigate("/syt/hospital/hospitalSet/add"); // push
  };

  // 跳转到修改医院组件
  // 需要传参就得用高阶函数形式
  const goUpdateHospital = (row:any) => {
    // return () => {
    //   navigate(`/syt/hospital/hospitalSet/edit/${id}`);
    // };
    // settitle("修改用户")
    settitle("修改用户")  
    setIsModalOpen(true);
    // console.log(row)
    setusername(row.username)
    setnickName(row.nickName)
    // setpassword(row.password)
    setuserid(row.id)
    // set

    // setpassword()
   
    // value2.current.input.value=
    // value3.current.input.value=row.password
    // console.log(value1.current.input.value,value2.current.input.value,value3.current.input.value)
  };
  //分配角色按钮
  const goAssignHospital =()=>{
    
  }
  // 选中的医院id列表数据
  const [selectedHospitalIds, setSelectedHospitalIds] = useState<Key[]>([]);

  // 复选框触发的事件
  const rowSelection = {
    // 全选&单选
    onChange1: (
      selectedRowKeys: Key[]
      // selectedRows: HospitalList
    ) => {
      // selectedRowKeys 选中的当前元素key的值组成的数组（我们之前设置rowKey为id，所以实际获取的是当前元素的id）
      // selectedRows 选中的当前元素组成的数组

      // 设置选中的医院id列表
      setSelectedHospitalIds(selectedRowKeys);
    },
    // 单选
    // onSelect: (record: any, selected: any, selectedRows: any) => {
    //   console.log(record, selected, selectedRows);
    // },
    // 全选
    // onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
    //   console.log(selected, selectedRows, changeRows);
    // },
  };
  //搜索框的事件
  const research =()=>{
    
  }
  ;
  //打印一下这个鬼东西
  // const inputValOpt=(value1)=>{
  //   console.log(value1)
  // }
  

  const [res,setres] = useState([])
  const batchRemoveHospitalList = async () => {
    await reqBatchRemoveHospitalList(selectedHospitalIds);
    message.success("批量删除成功");
  // 重新获取最新医院列表即可
    getHospitalList(current, pageSize);
  };
  //展示全部角色的模态框
  const showModalAgain = async(row) => {
    setIsModalOpenAgain(true);
    setusername(row.username);
    setuserid(row.id);
    // console.log(row)
    const res = await reqGetRoles(userid)
    console.log(res)
    setres(res)
    const resrole = res.allRolesList.map(item=>item.roleName)
    // const roleId = res.allRolesList.map(item=>item.id)
    //测试留用assignRoles
    console.log(resrole)
    // setRoleId(roleId)
    // console.log(roleId)
    setoptions(resrole)
   
    
  };

  const handleOkAgain = () => {

    setIsModalOpenAgain(false);
    let b = res.allRolesList.filter((item)=>{
      if(checkedList.includes(item.roleName)){return item}
    })
    const a = b.map(item=>item.id)
    // array.arr.map((item[,index,arr])=>{})
    // const roleId =a["id"]
    // setRoleId(a.id)
    console.log('123',a)  
    // console.log(userid);
    // console.log(roleId);
    const roleId = a
  //  setRoleId(a)
    reqToRoles(userid,roleId.join(","))
  };

  const handleCancelAgain = () => {
    setIsModalOpenAgain(false);
  };
//复选框
const CheckboxGroup = Checkbox.Group;

// const [options] = ['Apple', 'Pear', 'Orange'];
const [options,setoptions] = useState([]);
const defaultCheckedList = ['Apple', 'Orange'];

  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>(defaultCheckedList);
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);

  const onChange = (list: CheckboxValueType[]) => {
    setCheckedList(list);
    // setRoleId(list)
    console.log(list)
    // console.log(e)
    setIndeterminate(!!list.length && list.length < options.length);
    setCheckAll(list.length === options.length);
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? options : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  return (
    <Card>
      {/* 头部表单和按钮组件 */}
      {/*
        Form 表单组件
          form={form} 通过Form.useForm()得到，最终可以操作Form实例对象，从而完成表单校验、清空等操作
          layout="inline" 表单项布局方式，内联（水平）布局
          onFinish={onFinish} 当按钮设置htmlType="submit"时，点击这个按钮就会触发onFinish，此时会对整个表单进行校验，通过了，才会执行onFinish函数

        Form.Item 单个表单项组件
          name 表单项名称，也是将来收集的表单数据名称
          rules 表单校验规则
            required 必填
          message 校验失败的错误信息
      */}
      <Form form={form} layout="inline" onFinish={onFinish}>
        <Form.Item
          // 将表单字段更新为请求参数对应的字段
          name="username"
          // 不需要表单校验功能
          // rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input placeholder={"请输入内容"} />
        </Form.Item>
        <Form.Item>
          <Button type="primary"  htmlType="submit" icon={<SearchOutlined />} className="hospital-btn mb">
            {t("searchBtnText")}
          </Button>
          <Button onClick={reset}>{t("clearBtnText")}</Button>
        </Form.Item>
      </Form>

      <Button type="primary" onClick={showModal}>
        添加
      </Button>
      <Modal title={title} visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
       {/* 求求了，不写表单了咱们 */}
       用户名<Input   placeholder=""   value={username} onChange={handleUsernameChange}/><br/><br/>
       用户昵称<Input  placeholder=""   value={nickName} onChange={handleNicknameChange}/><br/><br/>
       用户密码<Input   placeholder=""  value={password} onChange={handlePasswordChange}/><br/><br/>
       {/* 用户名<Input   placeholder=""   ref={value1} defaultvalue={value1.current.input.value}/><br/><br/>
       用户昵称<Input  placeholder=""   ref={value2} defaultvalue={value2.current.input.value}/><br/><br/>
       用户密码<Input   placeholder=""  ref={value3} defaultvalue={value3.current.input.value}/><br/><br/> */}
       
      <button >点击</button>
      </Modal>
      {/*
        selectedHospitalIds.length 如果为0，代表没有选中，就要禁用
        selectedHospitalIds.length 如果为1,2,3，代表有选中，就要不禁用
      */}
      <Button type="primary" danger disabled={!selectedHospitalIds.length} onClick={batchRemoveHospitalList}>
        {t("batchDelBtnText")}
      </Button>

      {/* 底部表格和分页器 */}
      {/*
        Table 表格组件
          columns 决定表格渲染几列
          dataSource 决定表格每一行渲染什么数据
          bordered 带边框
          scroll 滚动条
          rowKey="id" 遍历的key属性的值用id
          pagination 分页器设置
            current 当前页码
            pageSize 每页条数
            total 总数
            showQuickJumper 是否显示快速跳转
            showSizeChanger 是否显示每页条数
            showTotal 显示总数
            onChange 当前页码发送变化触发的事件
            onShowSizeChange 每页条数发送变化触发的事件
          loading 加载中
          rowSelection 复选框
      */}
      <Table
        columns={columns}
        dataSource={reslist}
        bordered
        scroll={{ x: 1500 }}
        rowKey="id"
        pagination={{
          current,
          pageSize,
          total,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `${t("total")} ${total}`,
          onChange: getHospitalList,
          onShowSizeChange: getHospitalList,
        }}
        loading={loading}
        rowSelection={rowSelection}
      />
       <>
   
    </>
    </Card>
    
  );
}

export default HospitalSet;
